<!--
  Copyright 2019 Hackware SpA <human@hackware.cl>
  This file is part of "Hackware Userland" and licensed under the terms
  of the GNU Affero General Public License version 3, or (at your option)
  a later version. You should have received a copy of this license along
  with the software. If not, see <https://www.gnu.org/licenses/>.
-->

<template>
  <div class="add-funds-gateway">
    <VAlert
      v-show="error"
      context="danger"
    >
      <i class="fas fa-exclamation-triangle" />
      Ha ocurrido un <strong>error</strong>, por favor verifica
      que los campos estén llenados correctamente o contáctanos.
    </VAlert>
    <h2>Añadir fondos</h2>
    <form @submit.prevent="submitAddFunds">
      <SchemaForm
        :json-schema="jsonSchema"
      />
      <div class="text-right">
        <button
          id="btnAddFunds"
          type="submit"
          class="btn btn-primary btn-lg"
        >
          <i class="far fa-handshake" />
          Proceder
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import SchemaForm from '@/components/SchemaForm.vue';
import VAlert from '@/components/VAlert.vue';

export default {
  name: 'AddFundsGateway',
  components: {
    SchemaForm,
    VAlert,
  },
  data() {
    return {
      jsonSchema: {},
      error: false,
    };
  },
  beforeCreate() {
    this.$fetcher.haweseGet(`/gateways/${this.$route.params.gateway}/schemas/purchase`)
      .then((body) => { this.jsonSchema = this.setDefaults(body); });
  },
  methods: {
    setDefaults(jsonSchema) {
      const jsonSchemaCopy = jsonSchema;
      Object.entries(this.$route.query).forEach((tuple) => {
        const [key, value] = tuple;
        jsonSchemaCopy.properties[key].default = value;
      });
      return jsonSchemaCopy;
    },
    submitAddFunds(event) {
      const btnAddFunds = document.getElementById('btnAddFunds');
      this.error = false;
      btnAddFunds.setAttribute('disabled', true);

      this.$fetcher.hawesePost(
        `/gateways/${this.$route.params.gateway}/purchase`,
        event.target,
      ).then((body) => {
        if ('error' in body) {
          btnAddFunds.removeAttribute('disabled');
          this.error = true;
        } else {
          window.location.href = body.redirect_url;
        }
      });
    },
  },
};
</script>
